package com.lagou.handler;

import com.lagou.service.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import static com.lagou.boot.ServerBoot.HANDLER_MAPPING;

public class RpcRequestServiceHanlder extends ChannelInboundHandlerAdapter {

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object obj) throws Exception {

        //注意:  客户端将来发送请求的时候会传递一个参数:  UserService#sayHello#are you ok
        //1.判断当前的请求是否符合规则
        if(obj instanceof RpcRequest){

            RpcRequest rpcRequest = (RpcRequest) obj;
            //2.如果符合规则,调用实现类货到一个result
            Handler handler = HANDLER_MAPPING.get(rpcRequest.getRequestId());
            Object result =  handler.getMethod().invoke(handler.getService(), rpcRequest.getParameters());
            //3.把调用实现类的方法获得的结果写到客户端
            ctx.writeAndFlush(result);
        }
    }
}
